﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Logic.ClarizenObjects;
using Logic.ClarizenSvc;
using Logic;

namespace ClarizenGadget.Controllers
{
    public class TimeSheetController : Controller
    {
        public ActionResult Edit()
        {
            return View();
        }
        [HttpPost]
        [ValidateInput(false)]
        public ActionResult List(DateTime? start, DateTime? end, int? page, string userID, string projectID)
        {
            // get date bounds
            if(!start.HasValue)
            {
                start = DateTime.Now.AddDays(-7);
                end = DateTime.Now;
            }
            else if(!end.HasValue || end< start)
                end = start.Value.AddDays(7);
          
            Boolean hasMore;
            long totalCount;

            try
            {
                var sheet = TimeSheet.GetTimeSheet(start.Value, end.Value, page ?? 0, userID, projectID, out hasMore, out totalCount);
                return Json(new
                {
                    sheets = sheet.OrderBy(s => s.Value.WorkItem.Name).Select(s =>
                    {
                        var wi = s.Value.WorkItem;
                        foreach (TimeSheet val in s.Value.TimeSheets.Values)
                        {
                            val.Duration.Value = Math.Round(val.Duration.Value,2);
                        }
                        return new
                        {
                            wi.Name,
                            wi.ID,
                            wi.SYSID,
                            s.Value.TimeSheets,
                            wi.ActualEffort,
                            wi.RemainingEffort,
                            wi.ParentProject_Name,
                            wi.DueDateString,
                            wi.PercentCompleted,
                            wi.Parent_Name,
                            wi.Resources,
                            wi.IndividualReporting,
                            wi.Manager
                        };
                    }),
                    hasMore = hasMore,
                    totalCount = totalCount,
                });
            }
            catch (Exception e)
            {
                return Json(new GadgetResponse<Object>
                {
                    Status = GadgetResponseStatus.Error,
                    ErrorMessage = e.Message,
                    RedirectUrl = e.Message.ToLower().Contains("your session has expired") ? BLL.Users.GetAuthorizationLink() : ""
                });
            }
        }

        // used for updating and creating if the ID is null then we do a create other-wise nd update 
        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Edit(TimeSheet timeSheet)
        {
            try
            {
                GenericEntity ge = timeSheet.ToGenericEntity();

                var qc = new QueryComponent();

                EntityId id = timeSheet.ID;

                if (timeSheet.ID != null && !string.IsNullOrEmpty(timeSheet.ID.Value))
                    qc.UpdateEntity(ge);
                else
                    id = qc.CreateEntity(ge);

                return Json(new GadgetResponse<EntityId> { Data = id, Status = GadgetResponseStatus.Success });
            }
            catch (Exception e)
            {
                return Json(new GadgetResponse<Object> { Status = GadgetResponseStatus.Error, ErrorMessage = e.Message });
            }
        }

        [HttpPost]
        public ActionResult Delete(TimeSheet timeSheet)
        {
            try
            {
                new QueryComponent().DeleteEntity(timeSheet.ID);
                return Json(new GadgetResponse<Boolean> { Data = true, Status = GadgetResponseStatus.Success });
            }
            catch (Exception e)
            {
                return Json(new GadgetResponse<Object> { Status = GadgetResponseStatus.Error, ErrorMessage = e.Message });
            }
        }
    

        [HttpPost]
        public ActionResult Submit(List<String> EntityId)
        {
            try
            {
                LifecycleMessage msg = new LifecycleMessage { Ids = EntityId.Select(id => new EntityId {TypeName="TimeSheet", Value=id }).ToArray(), Operation = "Submit" };
                var qc = new QueryComponent();
                qc.Execute(msg);

                return Json(new GadgetResponse<Boolean> { Data = true, Status = GadgetResponseStatus.Success });
            }
            catch (Exception e)
            {
                return Json(new GadgetResponse<Boolean> { Data = false, Status = GadgetResponseStatus.Error, ErrorMessage = e.Message });
            }
        }
     
    }
}
